// 家谱数据
const familyData = {
  name: "始祖",
  children: [
    {
      name: "第一世A",
      children: [
        {
          name: "第二世A1",
          children: [
            { name: "第三世A11" },
            { name: "第三世A12" }
          ]
        },
        {
          name: "第二世A2",
          children: [
            { name: "第三世A21" },
            { name: "第三世A22" }
          ]
        }
      ]
    },
    {
      name: "第一世B",
      children: [
        {
          name: "第二世B1",
          children: [
            { name: "第三世B11" },
            { name: "第三世B12" }
          ]
        }
      ]
    }
  ]
};

// 渲染家谱函数
function renderFamilyTree(data, parentElement) {
  const nodeDiv = document.createElement("div");
  nodeDiv.className = "node";

  // 添加节点圆点和名字
  const circleSpan = document.createElement("span");
  circleSpan.className = "node-circle";
  nodeDiv.appendChild(circleSpan);

  const nameSpan = document.createElement("span");
  nameSpan.className = "node-name";
  nameSpan.textContent = data.name;
  nodeDiv.appendChild(nameSpan);

  // 如果有子节点，则递归渲染
  if (data.children && data.children.length > 0) {
    // 添加水平连线
    const horizontalLine = document.createElement("div");
    horizontalLine.className = "line line-horizontal";
    horizontalLine.style.width = `${data.children.length * 150}px`; // 根据子节点数量调整宽度
    parentElement.appendChild(horizontalLine);

    // 添加垂直连线
    data.children.forEach((child, index) => {
      const verticalLine = document.createElement("div");
      verticalLine.className = "line line-vertical";
      verticalLine.style.left = `${index * 150}px`; // 水平位置
      parentElement.appendChild(verticalLine);

      // 递归渲染子节点
      const childDiv = document.createElement("div");
      childDiv.style.position = "relative";
      childDiv.style.top = "20px"; // 节点向下偏移
      childDiv.style.left = `${index * 150}px`; // 水平位置
      renderFamilyTree(child, childDiv);
      parentElement.appendChild(childDiv);
    });
  }

  // 将当前节点添加到父元素
  parentElement.appendChild(nodeDiv);
}

// 初始化渲染
document.addEventListener("DOMContentLoaded", () => {
  const familyTreeContainer = document.getElementById("family-tree");
  renderFamilyTree(familyData, familyTreeContainer);
});